<?php

namespace Phones\MainBundle\Controller;

use Symfony\Component\HttpFoundation\Request,
    Symfony\Component\HttpFoundation\JsonResponse;

class SearchController extends AppController {

    public function indexAction(Request $request) {
        $response = array(
            'total'   => 0,
            'results' => array(),
            'count'   => 0
        );

        // get keyword from HTTP params
        $keyword = $request->request->get('keyword');
        // else try with url params
        if (empty($keyword)) {
            $keyword = $request->attributes->get('keyword');
        }

        $limit   = $request->request->get('limit');
        $ajax    = $request->request->get('ajax');

        if (! empty($keyword)) {
            $model = $this->getEntity('Model');

            $response['results'] = $model->search($keyword, $limit);
            $response['count']   = count($response['results']);
            $response['total']   = $model->searchTotal($keyword);
        }
        
        if ($ajax) {
            return new JsonResponse($response);
        } else {

            return $this->render('PhonesMainBundle:Search:index.html.twig', compact('keyword', 'response', 'brands'));
        }
    }
}